#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "pthread.h"


pthread_mutex_t lock;   
pthread_cond_t equal;  
pthread_cond_t equal1; 
int i=5,j=4,b=3;

void *thread1(void *data)
{     
      int x;
      int lood;
      pthread_mutex_lock(&lock);
    
      while(j>=0){
           if (i>0) {
		
		pthread_cond_wait(&equal1,&lock);
	   }
	   if (j == 0) {
            printf("RIGHT passed! LEFT pass\n");	
           }			
        
           if (j == 0) 
           break;
           j--;
	   printf("B: LEFT=%d,RIGHT=%d\n",i,j);
	
           pthread_mutex_unlock(&lock);
           }
        pthread_mutex_unlock(&lock);
        return NULL;
}

void *thread2(void *data)
{       int x;
        pthread_mutex_lock(&lock);	
	while(i>=0){
        if (i == 0) {
      
            printf("LEFT passed! RIGHT pass\n");
            pthread_cond_signal(&equal1);
            pthread_mutex_unlock(&lock);
            sleep(1);

        }
       
      	 if (i== 0) 
            break;
            i--;
	    printf("A: LEFT=%d,RIGHT=%d\n",i,j);
            pthread_mutex_unlock(&lock);
	} 
	pthread_mutex_unlock(&lock);



}

int main(int argc,char *argv[])
{
	pthread_t th_left;
	pthread_t th_right;
	
	void * retval;
	int loop;
	

        
	pthread_mutex_init(&lock,NULL);
	pthread_cond_init(&equal,NULL);	
	pthread_cond_init(&equal1,NULL);
	pthread_create(&th_left, NULL, thread1, 0);
	pthread_create(&th_right, NULL, thread2, 0);	

          
          int b,a;
	 srand(time( NULL )); 
        a= rand()%10;
        b= rand()%10;
        i=a;
        j=b;
   
       pthread_join(th_left, &retval);
       pthread_join(th_right, &retval);
       pthread_mutex_destroy(&lock);
       pthread_cond_destroy(&equal);
 
       return 0;
}


